package org.bing.zion.filter.comsat;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

public class ComsatEncoder extends ComsatCodec {
 
	@SuppressWarnings("rawtypes")
    public byte[] encode(Object msg) throws IOException {
		if (msg instanceof String) {
			String txt = (String) msg;
			return txt.getBytes();
		} else if (msg instanceof Map) {
			return encodeMap((Map) msg);
		} else {
			logger.error("Not support type " + msg.getClass().getName());
		}
		return null;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private byte[] encodeMap(Map map) throws IOException {
		Set<Map.Entry> entrys = map.entrySet();
		ByteArrayOutputStream baos = new ByteArrayOutputStream(256);
		baos.write('{');
		boolean append = false;
		for (Map.Entry entry : entrys) {
			Object key = entry.getKey();
			Object value = entry.getValue();
			if (value != null) {
				if (append) {
					baos.write(',');
				} else {
					append = true;
				}
				baos.write(key.toString().getBytes("UTF-8"));
				baos.write(':');
				if (value instanceof String) {
					String str = (String) value;
					for (int i = 0, len = str.length(); i < len; i++) {
						char c = str.charAt(i);
						if (c == ',') {
							baos.write('\'');
						}
						baos.write(c);
					}
				} else {
					baos.write(value.toString().getBytes());
				}
			}
		}
		baos.write('}');
		return baos.toByteArray();
	}
}
